<?php
declare (strict_types=1);

namespace app\exam\service\admin;

use app\common\service\BaseService;
use app\exam\logic\admin\PaperAnswerRecord as PaperAnswerRecordLogic;
use app\exam\logic\admin\PaperStudent as PaperStudentLogic;
use eduline\admin\libs\pagelist\ListItem;
use eduline\admin\page\PageList;
use think\annotation\Inject;
use think\facade\Request;

/**
 * 学员管理
 */
class PaperStudent extends BaseService
{
    /**
     * @Inject()
     *
     * @var PaperStudentLogic
     */
    protected $paperStudentLogic;

    /**
     * @Inject()
     *
     * @var PaperAnswerRecordLogic
     */
    protected $paperAnswerRecordLogic;

    /**
     * 列表
     *
     * @return \eduline\admin\page\interfaces\think\Response
     * @throws \think\db\exception\DbException
     */
    public function list(int $paperId)
    {
        $where = [
            'paper_id' => $paperId
        ];
        Request::has('title', 'get', true) && $where[] = ['title', 'like', '%' . Request::get('title/s') . '%'];
        $data = $this->paperStudentLogic->getList($where)->bindAttr('user', ['avatar_url', 'nick_name', 'phone'])->hidden(['user']);

        // 定义字段
        $keyList = [
            'user'        => ListItem::make('custom')->title('用户'),
            'create_time' => ListItem::make()->title('派发时间'),
            'exam_time'   => ListItem::make('custom')->title('考试时间'),
            'exam_status' => ListItem::make('custom')->title('状态'),
        ];
        // 设置表单
        $list = new PageList;
        // 表单字段
        $list->pageKey = $keyList;
        $list->datas   = $data;

        return $list->send();
    }

    /**
     * 添加学员
     *
     * @return \eduline\admin\page\interfaces\think\Response|\think\Response
     */
    public function created(int $paperId)
    {
        $data             = Request::post();
        $data['paper_id'] = $paperId;
        $res              = $this->paperStudentLogic->created($data);

        return $this->parseToData([], 1, '添加成功');

    }

    /**
     * 移除学员
     *
     * @param int $id
     * @return \think\Response
     */
    public function deletes($ids)
    {
        $this->paperStudentLogic->deletes($ids);

        return $this->parseToData([], 1, '移除成功');
    }

    /**
     * 导入学员
     *
     * @param int $paperId
     * @return \think\Response
     */
    public function import(int $paperId)
    {
        $attachId   = Request::post('attach_id/d');
        $configData = Request::post();
        $res        = $this->paperStudentLogic->doImportStudent($paperId, $attachId, $configData);

        return $this->parseToData($res, 1, '导入学员成功');
    }

    /**
     * 考试成绩列表
     *
     * @param int $paperId
     * @param int $userId
     * @return \think\Response
     */
    public function record(int $paperId, int $userId)
    {
        $datas = $this->paperAnswerRecordLogic->getAllAnswerRecordForAssign($paperId, $userId);

        return $this->parseToData($datas, 1);
    }
}
